#include "usrope.h"

int loginOrRegistFace()
{
	printf("   ^_^\n");
	printf("1，登录\n");
	printf("2，注册\n");
	printf("0，退出\n");
	printf("请输入操作选项:\n");
	int iNum = 0;
	//当没有正确输入时，循环将标准缓冲区中的数据读掉
	if (1 != scanf("%d", &iNum))
	{
		while ('\n' != getchar()){}
	}
	else
	{
		getchar();
	}
	return iNum;
}

static void getSTRFromSTDIN(char *arr, int count)
{
	//stdin->标准输入
	if (NULL == arr || count <= 0)
	{
		return;
	}
	fgets(arr, count, stdin);	
	//查找字符串中是否包含'\n'
	char *p = strchr(arr, '\n');
	if (NULL != p)//如果包含了，则将'\n'替换成'\0'
	{//表示将输入缓冲区中的数据全部读取掉了
		*p = '\0';
	}
	else//若没有找到'\n'，则表示缓冲区中还有数据
	{//循环读掉
		while ('\n' != getchar()){}
	}
}

void regist(UsrList *list)
{
	char caUsrName[NAME_LEN] = {'\0'};
	printf("请输入注册所用的用户名:\n");
	getSTRFromSTDIN(caUsrName, NAME_LEN);
	if (NULL != findUsrByName(list, caUsrName))
	{
		printf("注册失败-->该用户名已存在...\n");
	}
	else
	{
		char caUsrPwd[PWD_LEN] = {'\0'};
		printf("请输入注册所用密码:\n");
		getSTRFromSTDIN(caUsrPwd, PWD_LEN);
		//产生节点保存用户名及密码
		UsrNode *node = mkUsrNode();
		strcpy(node->caUsrName, caUsrName);
		strcpy(node->caUsrPwd, caUsrPwd);
		insert(list, node);
		saveUsrListToFile(PATH_NAME, list);
	}
}

UsrNode* login(UsrList *list)
{
	UsrNode *node = NULL;
	if (NULL != list)
	{
		char caUsrName[NAME_LEN] = {'\0'};
		printf("请输入用户名:\n");
		getSTRFromSTDIN(caUsrName, NAME_LEN);	
	
		node = findUsrByName(list, caUsrName);
		if (NULL == node)
		{
			printf("登录失败-->该用户名不存在...\n");
		}
		else
		{
			char caUsrPwd[PWD_LEN] = {'\0'};
			printf("请输入用户密码:\n");
			getSTRFromSTDIN(caUsrPwd, PWD_LEN);	
	 		
			if (0 == strcmp(caUsrPwd, node->caUsrPwd))
			{
				printf("登录成功...\n");
			}
			else
			{
				printf("登录失败-->用户密码错误...\n");
				node = NULL;
			}
		}
	}
	else
	{
		printf("参数有误...\n");
	}	

	return node;
}

UsrNode* loginOrRegistOpe(UsrList *list)
{
	if (NULL == list)
	{
		return NULL;
	}

	UsrNode *node = NULL;
	int iNum = 0;
	while (1)
	{
		iNum = loginOrRegistFace();
		switch (iNum)
		{
		case 1://登录
			node = login(list);
			break;
		case 2://注册
			regist(list);
			break;
		case 0://退出
			exit(EXIT_SUCCESS);
		default:
			printf("输入有误，请重新输入...\n");
			break;
		}
		if (NULL != node)
		{
			break;
		}
	}
	return node;
}

int usrOpeFace()
{
	printf("   ^_^\n");
	printf("1，显示全部用户信息\n");
	printf("2，显示本身信息\n");
	printf("3，修改密码\n");
	printf("0，退出登录\n");
	printf("请输入操作选项:\n");
	int iNum = 0;
	scanf("%d", &iNum);
	while ('\n' != getchar()){}

	return iNum;
}

void usrOpe(UsrList *list, UsrNode *node)
{
	if (NULL == list || NULL == node)
	{
		return;
	}

	int iNum = 0;
	while (1)
	{
		iNum = usrOpeFace();
		switch (iNum)
		{
		case 1: //显示全部信息
			display(list);
			break;
		case 2:
			printf("name:%s,pwd:%s,age:%d\n"
				   , node->caUsrName, node->caUsrPwd, node->iAge);
			break;
		case 3:
			printf("请输入新密码:\n");
			getSTRFromSTDIN(node->caUsrPwd, PWD_LEN);
			saveUsrListToFile(PATH_NAME, list);
			break;
		case 0:
			return;
		default:
			printf("输入有误...\n");
			break;
		}
	}
}









